import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Divider, Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { FormattedMessage } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { getList, removeField, cmsSiteTree } from './api';
import { getSysDeptTreelist } from '../../UserList/api';
import UpdateForm from './components/UpdateForm';
import Column from './components/column';

/**
 * @zh-CN 处理部门树格式
 * @param data
 */

const setTreeFormat = data => {
  const newData = [];
  data.map(item => {
    const obj = {
      id: item.deptId,
      value: item.deptId,
      title: item.deptName,
      pId: item.parentId,
      isLeaf: false,
    };
    newData.push(obj);
    return '';
  });
  return newData;
};
/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */

const getListData = async fields => {
  try {
    const data = await getList({ ...fields });
    if (data && data.code === 0 && data.data.list) {
      return { data: data.data.list, total: data.data.total };
    }
    message.error(data.msg || '请求失败，请重试');
  } catch (error) {
    message.error('请求失败，请重试');
    return false;
  }
};

const TableList = () => {
  const actionRef = useRef();

  const [treeData, setTreeData] = useState([]);

  const [columnData, setColumnData] = useState();
  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async id => {
    const hide = message.loading('正在删除');

    try {
      const msg = await removeField(id);
      hide();
      if (msg.code === 0) {
        message.success('删除成功！');
        if (actionRef.current) {
          actionRef.current.reload();
        }
        return true;
      }
      message.error(msg.msg || '删除失败，请重试');
      return false;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  /**
   * @zh-CN 获取部门树
   *
   * @param
   */
  const getSysDeptTreelistData = () => {
    getSysDeptTreelist().then(res => {
      if (res.code === 0) {
        setSysDeptData(setTreeFormat(res.data || []));
      }
    });
  };
  // 获取 类别树结构
  const getListTree = async fields => {
    try {
      const data = await cmsSiteTree({ ...fields });
      if (data.code === 0) {
        setTreeData(data.data);
        getSysDeptTreelistData();
        return;
      }
    } catch (error) {
      message.error('请求失败，请重试');
      return false;
    }
  };

  const [pagination, setPagination] = useState({ current: 1, pageSize: 20 });
  const ProTableOoChange = ({ current, pageSize }) => {
    setPagination({ current, pageSize });
  };

  useEffect(() => {
    getListTree();
  }, []);

  // 更新数据 组件 ------------------------------------------------------------------

  const [type, setType] = useState();

  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [updataData, setUpdataData] = useState({});
  const [sysDeptData, setSysDeptData] = useState();

  const currentIndex = actionRef?.current?.pageInfo?.total || 0; // 默认排序

  const closeUpdateForm = () => {
    handleUpdateModalVisible(false);
  };

  const setUpdateForm = (param, index) => {
    setType('updata');
    handleUpdateModalVisible(true);

    setUpdataData(param);
  };

  const updataSuccess = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  };

  // 添加
  const addUser = () => {
    setType('add');
    setUpdataData({});
    handleUpdateModalVisible(true);
  };
  // ----------------------------------------------结束------------------------------------------------------

  //--------------------------------------  culumn model        --------------------------
  const [columnVisible, setColumnVisible] = useState(false);
  const setColumn = data => {
    setColumnVisible(true);
    setColumnData(data);
  };
  const closeColumn = () => {
    setColumnVisible(false);
  };
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns = [
    {
      title: '序号',
      valueType: 'option',
      dataIndex: '',
      render(text, record, index) {
        return (
          <span key={index}>{(pagination.current - 1) * pagination.pageSize + index + 1}</span>
        );
      },
    },
    {
      title: '站点名称',
      dataIndex: 'siteName',
    },
    {
      title: '站点Url',
      dataIndex: 'siteUrl',
      hideInSearch: true,
    },
    {
      title: '描述',
      dataIndex: 'description',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'opt',
      valueType: 'option',
      render: (_, record, index) => {
        const text = (
          <>
            {record.delFlag !== 1 && (
              <>
                <Button type="link" onClick={() => setUpdateForm(record, index)}>
                  编辑
                </Button>
                <Divider type="vertical" />
                <Popconfirm
                  placement="topRight"
                  title="确实要删除此条信息吗？"
                  onConfirm={() => handleRemove(record.siteId)}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button type="link">删除</Button>
                </Popconfirm>
                <Button type="link" onClick={() => setColumn(record, index)}>
                  栏目
                </Button>
              </>
            )}
            {record.delFlag === 1 && (
              <>
                <Button type="link" danger disabled>
                  已删除
                </Button>
              </>
            )}
          </>
        );
        return <>{text}</>;
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey={record => record.siteId}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" key="primary" onClick={addUser}>
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        onChange={ProTableOoChange}
        request={getListData}
        columns={columns}
      />
      <UpdateForm
        visible={updateModalVisible}
        onCancel={closeUpdateForm}
        data={updataData}
        sysDeptData={sysDeptData}
        onSuccess={updataSuccess}
        type={type}
        currentIndex={currentIndex}
        indexTreeData={treeData}
      />

      <Column
        visible={columnVisible}
        onCancel={closeColumn}
        data={columnData}

        // onSuccess={updataSuccess}
      />
    </PageContainer>
  );
};

export default TableList;
